<?php

namespace api\wxapp\model;
use think\Db;
use think\Model;
use api\wxapp\model\CommentReply;
use api\wxapp\model\Like;
class Comment extends Model
{
    protected $table = 'sssc_app_comment';

    public function leftuser($query)
    {
        return $query->join('app_user t2','t2.id = t1.uid');
    }
    public function getfiled($query)
    {
        return $query->field('t1.*,t2.nickname,t2.img as userimg');
    }
    public function orderId($query)
    {
        return $query->order('t1.id desc');
    }
    public function getList($goods_id)
    {
        $query = self::alias('t1');
        $query = $this->leftuser($query);
        $query = $this->getfiled($query);
        $query = $this->orderId($query);
        $list = $query->where('t1.goods_id',$goods_id)->all()->each(function($item, $key) use($goods_id){
            $item['img'] = json_decode($item['img']);
            $item['reply'] = CommentReply::where('comment_id',$item['id'])->value('content');
            $map[] = ['uid','eq',$item['uid']];
            $map[] = ['goods_id','eq',$goods_id];
            $like = Like::where($map)->find();
            if($like){
                $item['like_id'] = $like['id'];
                $item['is_like'] = $like['type'];
            }else{
                $item['like_id'] = false;
                $item['is_like'] = false;
            }
        });
        return $list;
    }
    public function getScore($goods_id)
    {
        $list = db::name('app_goods_score')
            ->where('goods_id',$goods_id)
            ->field('score,count(*) as count')
            ->group("score")->select();
        $total = 0;
        $arr = array();
        foreach($list as $k=>$v){
            $total += $v['count'];
            $arr['count'.$v['score']] = $v['count'];
        }
        $arr['total'] = $total;
        return $arr;
    }
}
